package com.d3works.apps.businessproject.service;

import com.d3works.apps.base.db.Partner;
import com.d3works.apps.businessproject.service.app.AppBusinessProjectService;
import com.d3works.apps.purchase.db.PurchaseOrder;
import com.d3works.apps.purchase.service.PurchaseOrderService;
import com.d3works.apps.sale.db.SaleOrder;
import com.d3works.apps.sale.db.SaleOrderLine;
import com.d3works.apps.supplychain.service.PurchaseOrderLineServiceSupplyChain;
import com.d3works.apps.supplychain.service.PurchaseOrderSupplychainService;
import com.d3works.apps.supplychain.service.SaleOrderPurchaseServiceImpl;
import com.d3works.exception.D3worksException;
import com.d3works.inject.Beans;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.util.List;

public class ProjectPurchaseServiceImpl extends SaleOrderPurchaseServiceImpl {

  @Inject
  public ProjectPurchaseServiceImpl(
      PurchaseOrderSupplychainService purchaseOrderSupplychainService,
      PurchaseOrderLineServiceSupplyChain purchaseOrderLineServiceSupplychain,
      PurchaseOrderService purchaseOrderService) {
    super(
        purchaseOrderSupplychainService, purchaseOrderLineServiceSupplychain, purchaseOrderService);
  }

  @Override
  @Transactional(rollbackOn = {Exception.class})
  public PurchaseOrder createPurchaseOrder(
      Partner supplierPartner, List<SaleOrderLine> saleOrderLineList, SaleOrder saleOrder)
      throws D3worksException {
    PurchaseOrder purchaseOrder =
        super.createPurchaseOrder(supplierPartner, saleOrderLineList, saleOrder);

    if (purchaseOrder != null
        && saleOrder != null
        && Beans.get(AppBusinessProjectService.class).isApp("business-project")) {
      purchaseOrder.setProject(saleOrder.getProject());
    }

    return purchaseOrder;
  }
}
